package org.thunms.framework.utils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;


/**
 * 根据日期字符串长度判断是长日期还是短日期。只支持yyyy-MM-dd，yyyy-MM-dd HH:mm:ss两种格式。
 * 扩展支持yyyy,yyyy-MM日期格式
 * @author wanglp
 *
 */
public class CustomDateTypeAutoEditor extends PropertyEditorSupport {
	public static final DateFormat DF_LONG = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final DateFormat DF_SHORT = new SimpleDateFormat("yyyy-MM-dd");
	public static final DateFormat DF_YEAR = new SimpleDateFormat("yyyy");
	public static final DateFormat DF_MONTH = new SimpleDateFormat("yyyy-MM");
	/**
	 * 短类型日期长度
	 */
	public static final int SHORT_DATE = 10;

	public static final int YEAR_DATE = 4;

	public static final int MONTH_DATE = 7;

	public void setAsText(String text) throws IllegalArgumentException {
		//首先判断是否为null
		if (StringUtils.isBlank(text)) {
			setValue(null);
		}else{
			//当不为null才做以下处理
			text = text.trim();
			try {
				if (text.length() <= YEAR_DATE) {
					setValue(DF_YEAR.parse(text));
				} else if (text.length() <= MONTH_DATE) {
					setValue(DF_MONTH.parse(text));
				} else if (text.length() <= SHORT_DATE) {
					setValue(DF_SHORT.parse(text));
				} else {
					setValue(DF_LONG.parse(text));
				}
			} catch (ParseException ex) {
				IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex.getMessage());
				iae.initCause(ex);
				throw iae;
			}
		}
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	public String getAsText() {
		Object value=getValue();
		return (value != null ? DF_LONG.format((Date)value) : null);
	}
}
